import { asyncRouterMap, constantRouterMap } from '@/config/router.config'
import { RouterMockData } from '@/mock/services/routerData'
import { getUserMenues } from '@/api/blog'

/**
 * 包装后台返回的动态路由
 * @param sourceAsyncRouterMap 动态路由信息
 * @returns {*} 返回包装的路由信息
 */
function wrapperDnamicRouterData(sourceAsyncRouterMap) {
  for (var menuItem of sourceAsyncRouterMap) {
    hackComponentInfo(menuItem)
  }
  return sourceAsyncRouterMap
}

/**
 * 修改路由的空间信息
 * @param menue 路由的根级菜单
 */
function hackComponentInfo(menue) {
  // 加载动态组件
  if (menue.componentPath) {
    menue.component = (() => import(`@/${menue.componentPath}`))
  }
  // 没有子节点时移除子元素
  if (menue.children && menue.children.length === 0) {
    delete menue.children
  }
  if (menue.children && menue.children.length > 0) {
    for (var child of menue.children) {
      hackComponentInfo(child)
    }
  }
}

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permission, route) {
  if (route.meta && route.meta.permission) {
    let flag = false
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i])
      if (flag) {
        return true
      }
    }
    return false
  }
  return true
}

/**
 * 单账户多角色时，使用该方法可过滤角色不存在的菜单
 *
 * @param roles
 * @param route
 * @returns {*}
 */
// eslint-disable-next-line
function hasRole(roles, route) {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(roles.id)
  } else {
    return true
  }
}

function filterAsyncRouter(routerMap, roles) {
  const accessedRouters = routerMap.filter(route => {
    if (hasPermission(roles.permissionList, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        getUserMenues().then(res => {
          //const asyncRouterMap = wrapperDnamicRouterData(RouterMockData)
          const asyncRouterMap = wrapperDnamicRouterData(res.data)
          commit('SET_ROUTERS', asyncRouterMap)
          resolve()
        }).catch(err => {
          reject(err)
        })

      })
    }
  }
}

export default permission
